from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response

from apps.orders.models import OrderInfo
from apps.meiduo_admin.utils import NumPage
from apps.meiduo_admin.serialziers.orders import OrdersSerialzier
from rest_framework.viewsets import ReadOnlyModelViewSet


class OrderView(ListAPIView):
    # 指定查询集
    queryset = OrderInfo.objects.all()
    # 指定序列化器
    serializer_class = OrdersSerialzier
    # 指定权限
    permission_classes = [IsAdminUser]
    # 指定分页
    pagination_class = NumPage

    # 重写获取数据方法，根据不同数据获取不同的内容
    def get_queryset(self):
        # 获取keyword关键字
        key_world = self.request.query_params.get('keyword')
        # 根据关键字返回不同数据内容
        if key_world == '' or key_world == None:
            return self.queryset
        else:
            return OrderInfo.objects.filter(order_id__contains=key_world)


class OrderDetailView(RetrieveAPIView):
    # 指定查询集
    queryset = OrderInfo.objects.all()
    # 指定序列化器
    serializer_class = OrdersSerialzier
    # 指定权限
    permission_classes = [IsAdminUser]

    def put(self, request, pk):
        # 获取修改的状态信息
        data = request.data
        # 查询修改的订单
        order = self.get_object()
        order.status = data['status']
        order.save()
        return Response({'messgae': 'ok', 'status': data['status']})
